package JDBC;

import util.JDBCUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class jdbc_study6 {

    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;
        try {
            conn = DriverManager.getConnection("jdbc:mysql:///db","root","root");
            //开启事务
            conn.setAutoCommit(false);
            String sql1 = "update account set balance = balance - ? where name = ?";
            String sql2 = "update account set balance = balance + ? where name = ?";
            //用PrepareStatement方法来输入
            pstmt1 = conn.prepareStatement(sql1);
            pstmt2 = conn.prepareStatement(sql2);
            pstmt1.setDouble(1,500);
            pstmt1.setString(2,"老王");
            pstmt2.setDouble(1,500);
            pstmt2.setString(2,"老李");

            pstmt1.executeUpdate();
            //手动制作异常
            int i = 3/0;
            pstmt2.executeUpdate();

            conn.commit();
            //提交事务
        } catch (Exception e) {
            try {
                if(conn!=null) {
                    conn.rollback();
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
        finally {
            JDBCUtils.close(pstmt1,conn);
            JDBCUtils.close(pstmt2,conn);
        }
    }
}
